﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace _43流的读写器
{
    internal class Program
    {
        //包装文件流
        private static void Main1(string[] args)
        {
            using (var fs = File.Create(@"D:\test123.txt"))
            {
                using (var writer = new StreamWriter(fs))
                {
                    while (true)
                    {
                        string str = Console.ReadLine();
                        if (str == "Exit()")
                        {
                            break;
                        }
                        writer.WriteLine(str);
                    }
                    writer.Flush();
                }
            }
        }

        //包装网络流

        private static void Main(string[] args)
        {
            TcpClient tcpClient = new TcpClient();//创建Tcp客户端
            try
            {
                tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.111.222"), 8080));//连接
            }
            catch (Exception e)
            {
                Console.WriteLine("连接失败:" + e);
            }
            Console.WriteLine("连接成功");
            Stream stream = tcpClient.GetStream();//拿到网络流

            //创建读取和写入器(包装网络流)
            StreamReader reader = new StreamReader(stream);
            StreamWriter writer = new StreamWriter(stream);

            new Thread(Read).Start(reader);

            //写入流(发送消息)
            while (true)
            {
                string str = Console.ReadLine();
                if (str == "Exit()")
                {
                    break;
                }
                writer.WriteLine(str);
                writer.Flush();
            }
        }

        private static void Read(Object readerObj)
        {
            StreamReader reader = readerObj as StreamReader;
            while (true)
            {
                Console.WriteLine("接收");
                string str = reader.ReadLine();
                Console.WriteLine(str);
            }
        }
    }
}